package handler

import (
	"Gin/Api/request"
	"Gin/global/model"
	"Gin/global/pkg"
	"ViewSrv/view"
	"VipSrv/vip"
	context2 "context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

func VideoView(context *gin.Context) {
	var VideoViewRequest request.VideoViewRequest
	if err := context.ShouldBind(&VideoViewRequest); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	videoView, err := model.ViewClient.VideoView(context2.Background(), &view.VideoViewRequest{
		UserId:  VideoViewRequest.UserId,
		VideoId: VideoViewRequest.VideoId,
		IsVip:   VideoViewRequest.IsVip,
	})
	_, err = model.VipClient.VipExpireTip(context2.Background(), &vip.VipExpireTipRequest{UserId: VideoViewRequest.UserId})
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	set, _ := json.Marshal(&videoView)
	Upgrader := websocket.Upgrader{WriteBufferSize: 1024, ReadBufferSize: 1024}
	conn, err := Upgrader.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	key := fmt.Sprintf("user:%d:tips", VideoViewRequest.UserId)

	go func() {
		rabbitmq := pkg.NewRabbitMQSimple("" +
			key)
		msgs := rabbitmq.ConsumeSimple()
		for msg := range msgs {
			conn.WriteMessage(websocket.TextMessage, msg.Body)
		}
	}()

	conn.WriteMessage(websocket.TextMessage, set)
	ticker := time.NewTicker(30 * time.Second)
	count := 0
	for _ = range ticker.C {
		if videoView.TryView == 1 {
			err = conn.WriteMessage(websocket.TextMessage, []byte("您还不是会员，试看结束"))
			conn.Close()
			return
		}
		err = conn.WriteMessage(websocket.TextMessage, []byte("尝试同步播放进度"))
		if err != nil {
			return
		}
		_, err = model.ViewClient.ViewLen(context2.Background(), &view.ViewLenRequest{
			UserId:   VideoViewRequest.UserId,
			VideoId:  VideoViewRequest.VideoId,
			VideoLen: int64((count + 1) * 30),
		})
		if err != nil {
			err = conn.WriteMessage(websocket.TextMessage, []byte("同步播放进度失败"))
			return
		}
		err = conn.WriteMessage(websocket.TextMessage, []byte("同步播放进度成功"))
	}
}
